/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="image-table__container">
        <div class="table-data">
            <sf-grid>
                <sf-toolbar ref="toolbar">
                    <sf-button
                        class="btn-blank"
                        icon-cls="iconsip-refresh"
                        @click="_onRefresh">
                        <lang>刷新</lang>
                    </sf-button>
                    <sf-button
                        ref="submit"
                        class="creat-button btn-blank"
                        icon-cls="iconxinzeng2"
                        @click="_addImageModel">
                        <lang>新增notebook镜像</lang>
                    </sf-button>
                    <sf-searchfield
                        v-model="searchParams.keyword"
                        class="pull-right"
                        placeholder="请输入关键字"
                        @trigger="_startSearch"
                        @clear="_startSearch" />
                </sf-toolbar>
                <sf-table
                    ref="table"
                    :options="options_fix"
                    @pagechange="_onPageChange"
                    @sizechange="_onSizeChange">
                    <sf-table-column :default-width="30"
                                     type="index">
                        <lang>序号</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="name"
                        :default-width="100">
                        <lang>服务镜像名称</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="imageAddress"
                        :title="_('服务镜像地址')"
                        :default-width="100">
                        <lang>服务镜像地址</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="description"
                        :default-width="100">
                        <lang>描述</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="updateTime"
                        :default-width="120">
                        <lang>最近更新时间</lang>
                    </sf-table-column>
                    <sf-table-column data-index="opr"
                                     :default-width="100">
                        <lang>操作</lang>
                    </sf-table-column>
                    <!--额外操作-->
                    <template slot="createTime"
                              slot-scope="{value}">
                        <span>{{ encodeTime(value) }}</span>
                    </template>
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="table-opr">
                            <a
                                class="link-btn"
                                @click="_editImageModel(record)">
                                <lang>编辑</lang>
                            </a>
                            <a
                                class="link-btn"
                                @click="_deleteSource(record)">
                                <lang>删除</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
            </sf-grid>
        </div>
    </div>
</template>

<script>

import { encodeDate } from 'src/util/format';
const PAGE_COUNT = 20;

import urlAdapter from 'src/home/mod_common/url_adapter';

import store from 'src/vuex/store';
let userID = store.state.userId;
const IMAGE_URLS = {
    get: urlAdapter(`user/${userID}/image`),
    delete: urlAdapter('image'),
    post:urlAdapter(`user/${userID}/image`),
    update:urlAdapter('image')
};

import addImageForm from 'src/home/mod_cluster/common/common_form/add_image_form.vue';

export default{
    components:{
        pageTitle,
        flowImageTable
    },
    data() {
        return {
             searchParams =  {
                pageSize: PAGE_COUNT,
                pageNum: 0,
                keyword:''
            },
            options_fix = {
                bufferView: false,
                selectionHide: true,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')]
                }
            }
        }
    },
     async mounted () {
        await this.refreshGrid();
    },
    computed: {
        userId () {
            return this.$store.state.userId;
        }
    },
    methods:{
        async refreshGrid () {
            this.$mask();
            const GET_IMAGE_URL = `${IMAGE_URLS.get}`;
            let jsonData = await this.$ajax.get(GET_IMAGE_URL, this.searchParams);
            this.$unmask();
            let table = this.$refs.table;
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                // @ts-ignore
                table.loadData([]);
                return;
            }
            if (!table) {
                return;
            }
            // @ts-ignore
            table.getPagination().setTotal(data.total);
            // @ts-ignore
            table.loadData(data.list || []);
        },

        // 新增/编辑算法的卡片信息
        async ajaxSubmitImageInfo (params, formWin, fetch = 'post') {
            formWin.$mask();
            const ADD_TYPE_URL = `${IMAGE_URLS.post}`;
            // @ts-ignore
            const QUERY_URL = fetch === 'post' ? ADD_TYPE_URL : `${IMAGE_URLS.update}/${params.id}`;
            let jsonData = await this.$ajax[fetch](QUERY_URL, params);
            formWin.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('保存失败'));
            }
            this.$ok(_('保存成功'));
            formWin.hide();

            await this.refreshGrid();
        },

        //删除数据源

        _deleteSource (record) {
            let item = record;
            let params = {};
            let title = '';
            if (item) {
                // @ts-ignore
                params.id = item.id;
                title = item.name;
            }
            // @ts-ignore
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}服务镜像吗？', title),
                msg:'',
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        // @ts-ignore
                        this.ajaxDeleteSource(params);
                    }
                }
            });
        },

        // 执行删除操作
        async ajaxDeleteSource (params) {
            this.$mask();
            let jsonData = await this.$ajax.delete(`${IMAGE_URLS.delete}/${params.id}`, params);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('删除失败'));
            }
            this.$ok(_('删除成功'));

            this.refreshGrid();
        },

        // 新增数据源弹窗
        _createImageFormWin () {
            if (!this.imageFormWin) {
                this.imageFormWin = this.$modal(addImageForm, {
                    autoDestory: true
                });
            }
            return this.imageFormWin;
        },

        //新增notebook镜像服务
        _addImageModel () {
            this._createImageFormWin();
            this.imageFormWin.open({
                reset: true,
                title: _('新增服务镜像'),
                submit: () => {
                    let ajaxParams = this.imageFormWin.formRoot.getJsonValue();
                    ajaxParams.imageAddress = ajaxParams.address;
                    this.ajaxSubmitImageInfo(ajaxParams, this.imageFormWin);
                }
            });
        },

        //编辑notebook镜像服务
        _editImageModel (record) {
            let formWin = this._createImageFormWin();
            // @ts-ignore
            record.address = record.imageAddress;
            formWin.formRoot.setJsonValue(record);
            formWin.open({
                title: _('编辑服务镜像'),
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    // @ts-ignore
                    ajaxParams.id = record.id;
                    ajaxParams.imageAddress = ajaxParams.address;
                    this.ajaxSubmitImageInfo(ajaxParams, formWin, 'put');
                }
            });
        },

        _onRefresh () {
            this.refreshGrid();
        },

        _startSearch () {
            this.refreshGrid();
        },

        _onPageChange (pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.refreshGrid();
        },
        _onSizeChange (nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        },

        encodeTime (time) {
            return encodeDate(time);
        }
    }
    
};
</script>

